package cn.edu.t9.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.t9.domain.Person;
import cn.edu.t9.service.PersonService;

public class MainServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		PersonService service=new PersonService();
		List<Person> persons=service.getAll();
		System.out.print(persons);
		resp.setCharacterEncoding("utf-8");
		String opr=req.getParameter("opr");
		if("json".equals(opr)){
			
			StringBuilder json=new StringBuilder();
			json.append('[');
			for(Person person:persons){
				json.append('{');
				json.append("id:").append(person.getId()).append(',');
				json.append("name:\'").append(person.getName()).append("\',");
				json.append("sex:'").append(person.getSex()).append('\'');
				json.append('}').append(',');
			}
			json.deleteCharAt(json.length()-1);
			json.append("]");
			req.setAttribute("json", json.toString());
			req.getRequestDispatcher("json.jsp").forward(req, resp);
		}else if("xml".equals(opr)){

			req.setAttribute("persons", persons);
			req.getRequestDispatcher("xml.jsp").forward(req, resp);
		}
		
	}
	
}
